var util = require('../../libs/util.js');
var app = getApp();
var moment = require('../../libs/moment.min.js');
moment.locale('zh-cn');
Page({
  data: {
    shopData: [],
    originalShopData:[],
    selected: false,
    orderId: "",
    type: ''
  },
  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/index/index'
    }
  },
  onShow:function(e){
    var that = this;
    wx.getStorage({
      key: 'path_shop',
      success: function (res) {
        if (res.data) {
          var _shopData = that.data.shopData;
          _shopData.push({ name: res.data.name, type: 'shop', address: res.data.address, longitude: res.data.longitude,latitude:res.data.latitude, shop_time: '00:00', id: res.data.value, value: res.data.value });
          that.setData({
            shopData: _shopData
          });
          wx.removeStorage({
            key: 'path_shop',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'path_map',
      success: function (res) {
        if (res.data) {
          var shopData = res.data, _shopData = [];
          for (var i = 0; i < shopData.length; i++) {
            if (shopData[i].type == 'shop') {
              _shopData.push(shopData[i]);
            }
          };
          that.setData({
            shopData: _shopData
          });
          wx.removeStorage({
            key: 'path_map',
            success: function (res) {
            }
          });
        }
      }
    });
  },
  onLoad: function (e) {
    wx.setNavigationBarTitle({ "title": app.appName +"--修改配送点" });
    wx.showToast({
      title: "页面加载中\n请稍候...",
      icon: "loading",
      duration: 5000
    });
    this.setData({
      orderId: e.id,
      warehouse: e.warehouse
    })
    this.loadData();
  },
  onReady: function () {
    wx.hideToast()
  },
  loadData() {
    wx.showLoading({
      title: '加载数据中...',
    });
    var that = this;
    util.getData("deliveryPointList", { orderId: that.data.orderId, warehouse: that.data.warehouse }, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (res.data.success) {
        var _warehouseData = res.data.data[1][0];
        var coord = String(_warehouseData.coord).split(",");
        var path_name = '';
        var warehouseData = { name: _warehouseData.name, type: 'warehouse', address: _warehouseData.address, latitude: coord[0], longitude: coord[1], depart_time: '02:00', loading_time: '01:00', id: _warehouseData.wh_id, value: _warehouseData.wh_id,is_custom_distance:_warehouseData.is_custom_distance };
        var data = res.data.data[0], _data = [], originalShopData = [];
        for (var i = 0; i < data.length; i++) {
          if(i==0){
            path_name = data[i].path_name
          }
          var coord = String(data[i].coord).split(",");
          _data.push({ name: data[i].name, type: 'shop', address: data[i].address, longitude: coord[1], latitude: coord[0], shop_time: data[i].shop_time, id: data[i].shop_id, value: data[i].shop_id });
          originalShopData.push({ name: data[i].name, type: 'shop', address: data[i].address, longitude: coord[1], latitude: coord[0], shop_time: data[i].shop_time, id: data[i].shop_id, value: data[i].shop_id });
        };
        that.setData({
          shopData: _data,
          originalShopData: originalShopData,
          warehouseData: warehouseData,
          path_name: path_name
        });
      }
    });
  },
  shopSelect: function (e) {
    console.log(e)
    var shopData = this.data.shopData;
    for (var i = 0; i < shopData.length; i++) {
      shopData[i].checked = shopData[i].value == e.detail.value;
      if (shopData[i].value == e.detail.value) {
        this.setData({
          selected: true,
          shop: shopData[i]
        })
      }
    }
    this.setData({
      shopData: shopData
    });
  },
  deleteShop:function(){
    var shopData = this.data.shopData,_shopData = [];
    for (var i = 0; i < shopData.length; i++) {
      if(!shopData[i].checked){
        _shopData.push(shopData[i]);
      }
    }
    this.setData({
      shopData: _shopData
    });
  },
  changeShoptime:function(){
    var that = this;
      if(that.data.shop){
        var shop_time = that.data.shop.shop_time;
        that.setData({
          //currentId:e.currentTarget.dataset.id,
          datetime_picker:new Date(shop_time).getTime(),
          datetime_picker_show:true,
          old_shop_time:shop_time
        })
      }else{
        wx.showToast({
          title: '请选择收货点',
          image: '/images/wrong.png',
          duration: 3000
        });
      }
  },
  datetimePicker:function(e){
    //console.log(moment(e.detail).format('YYYY-MM-DD HH:mm:ss'))
    var shop_time = moment(e.detail).format('YYYY-MM-DD HH:mm');
    this.setData({
      shop_time:shop_time
    })
  },
  datetimePickerCancel:function(){
    this.setData({
      datetime_picker_show:false
    })
  },
  datetimePickerConfirm:function(){
    var that = this;
    that.setData({
      datetime_picker_show:false,
      "shop.shop_time":that.data.shop_time
    })
    util.putData("/atapi/delivery/process/changeShoptime", {
      id: that.data.orderId,
      unionid: app.globalData.unionid,
      CO_ID: app.globalData.CO_ID,
      user_id: app.globalData.user_id,
      truename: app.globalData.truename,
      shop: that.data.shop.id,
      shop_time: that.data.shop.shop_time,
      old_shop_time:that.data.old_shop_time,
      name:that.data.shop.name
    }, function (res, error) {
      console.log(res);
      console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
      }
      if (res.data.success) {
        var shopData = that.data.shopData;
        for(var i=0;i<shopData.length;i++){
           if(shopData[i].id == that.data.shop.id){
            shopData[i].shop_time == that.data.shop.shop_time;
           }
        }
        that.setData({
          shopData:shopData
        })
        wx.showToast({
          title: res.data.data,
          icon: 'success',
          duration: 3000
        });
      }else{
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.png',
          duration: 3000
        });
      }
    });
  },
  addShop:function(){
    wx.navigateTo({
      url: '/pages/index/shopList?warehouse='+this.data.warehouse
    })
  },
  showMap: function () {
    var shopData = this.data.shopData, _shopData = [];
    _shopData.push(this.data.warehouseData);
    for (var i = 0; i < shopData.length; i++) {
      _shopData.push(shopData[i]);
    };
    wx.setStorage({
      key: "path_map",
      data: _shopData
    });
    wx.navigateTo({
      url: '/pages/index/map'
    })
  },
  confirmData: function () {
    var that = this;
    wx.showLoading({
      title: '更换配送点中...',
    });
    var shopData = that.data.shopData, _shopData = [],_path_shop_name = new Array();
    for (var i = 0; i < shopData.length;i++){
      _shopData.push({
        id: shopData[i].id,
        name: shopData[i].name,
        type: 'shop',
        address: shopData[i].address,
        shop_time: '00:00',
        longitude: shopData[i].longitude,
        latitude: shopData[i].latitude,
        sort: (i + 2)
      });
      _path_shop_name[i] = String(shopData[i].name).replace("深圳", "").replace("东莞", "").replace("站", "");
    };
    var path_name = that.data.warehouseData.name + ' - ' + _path_shop_name.join("+");
    util.putData("changeDeliveryPoint", {
      orderId: that.data.orderId,
      shopData: JSON.stringify(_shopData),
      oldShopData: JSON.stringify(that.data.originalShopData),
      shopNumber: _shopData.length,
      path_name: path_name,
      is_custom_distance:this.data.warehouseData.is_custom_distance,
      openid: app.globalData.openid,
      'CO_ID': app.globalData.CO_ID,
      'user_id': app.globalData.user_id,
      'truename': app.globalData.truename
    }, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
      }
      if (res.data.success) {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000,
          success: function () {
            // app.socket.emit('delivery', {
            //   TO: 'u' + app.globalData.user_id,
            //   content: '客服已变更路线，是否重启加载？',
            //   action:'restart',
            //   delivery:that.data.orderId
            // });
            setTimeout(function () {
              wx.redirectTo({
                url: '/pages/schedule/schedule'
              })
            }, 2000);
          }
        });
      }
    });
  },
  cancelConfirmData: function () {
    wx.redirectTo({
      url: '/pages/schedule/schedule'
    })
  }
});